<template>
  <!-- 选择试题 -->
  <el-drawer
    title="选择试题"
    append-to-body
    :visible.sync="topicDialogVisible"
    direction="rtl"
    size="60%"
    :before-close="handleClose"
  >
    <el-container ref="addExamContent" style="height: 100%">
      <el-header ref="addExamHeader" height="auto">
        <el-form ref="form" :model="form" :rules="rulesForm">
          <el-form-item label="试题排序" v-if="this.course !=1">
            <el-radio-group v-model="disorder" @change="changeQuesDisorder" style="width: 100%">
              <el-radio-button :label="0">正序</el-radio-button>
              <el-radio-button :label="1">乱序</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-row :gutter="50">
            <el-col :span="12">
              <el-form-item label="试题描述" prop="keyword">
                <el-input style="width: 100%" v-model="form.keyword" placeholder="试题描述" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择题库" prop="quesCateId">
                <el-input placeholder="请选择题库" :value="current.name" type="text" readonly>
                  <template slot="suffix">
                    <el-button class="el-icon-edit" @click="checkSort" type="text">选择题库</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="题型" prop="type">
                <el-select style="width: 100%" v-model="form.type" placeholder="请选择" filterable clearable>
                  <el-option
                    v-for="item in testType"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="难易度" prop="quesLevel">
                <el-select style="width: 100%" v-model="form.quesLevel" placeholder="请选择" filterable clearable>
                  <el-option
                    v-for="item in levelList"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col style="display: flex;justify-content: center">
              <el-button type="primary" round @click="getDataList">查询</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-header>
      <el-main ref="addExamMain" :style="addExamMain" v-loading="dataListLoading">
        <h3
          class="add-exam-list-select-h3"
          ref="addExamMainH3"
          style="border-bottom: 1px solid #333"
        >
          <el-checkbox v-model="isAllCheck" @change="examDataAllList" :disabled="!dataList.length" />
          <span>全选</span>
        </h3>
        <ul class="add-exam-list-select" ref="addExamMainList" :style="addExamMainList">
          <li v-for="x in dataList" :key="x.id">
            <h3 class="add-exam-list-select-h3">
              <el-checkbox v-model="x.status" @change="examDataList($event,x)" />
              <span v-html="decode(x.info)" />
            </h3>
            <ul>
              <li
                v-for="(i, index) in x.questionOptionEntities"
                :key="index"
              >{{i.key}}. {{i.option}}</li>
            </ul>
            <div class="add-exam-list-select-answer">
              <p>标准答案: {{x.answ}}</p>
              <p>
                <span>
                  难度:
                  <template v-if="parseInt(x.level) === 0">低</template>
                  <template v-else-if="parseInt(x.level) === 1">中</template>
                  <template v-else>高</template>
                </span>
              </p>
            </div>
          </li>
          <li v-if="!(dataList.length)" class="noData">暂无数据，请重新搜索或添加</li>
        </ul>
        <div class="learn-drawer-range-box-buttons" ref="addExamMainFooter">
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="page"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
        <div class="learn-drawer-range-box-buttons add-exam-footer" ref="addExamFooter">
          <el-button type="danger" round @click="handleClose">关闭</el-button>
          <el-button type="primary" round @click="onSubmit">选择</el-button>
        </div>
        <el-dialog
          title="分类管理"
          :visible.sync="dialogFormVisible"
          :show-close="false"
          append-to-body
          width="30%"
        >
          <paper-cate
            ref="paperCate"
            v-if="paperCate"
            :setCurrent="setCurrent"
            :current="current"
            :url="{
                                update:'/exam-admin/ques/cate/update',
                                save:'/exam-admin/ques/cate/save',
                                delete:'/exam-admin/ques/cate/delete',
                                tree:'/exam-admin/ques/cate/tree'
                                }"
          />
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </el-drawer>
</template>

<script>
import paperCate from './../../views/modules/paper/papercate'
import { decodeSrc } from '../../utils/htmlUtils'

export default {
  name: 'selectTopic',
  data() {
    return {
      dialogFormVisible: false,
      current: {},
      paperCate: false,
      topicDialogVisible: false,
      addExamMain: {
        height: '31.5%',
        padding: ' 0 30px',
        overflow: 'hidden'
      },
      addExamMainList: {
        height: '87%'
      },
      form: {
        keyword: '',
        quesCateId: '',
        type: '',
        quesLevel: ''
      },
      rulesForm: {
        quesCateId: [
          { required: true, message: '请选择所属工种', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择题型', trigger: 'blur' }]
      },
      dataList: [],
      testType: [
        {
          key: 1,
          value: '单选'
        },
        {
          key: 2,
          value: '多选'
        },
        {
          key: 3,
          value: '判断'
        },
        {
          key: 4,
          value: '填空'
        },
        {
          key: 5,
          value: '简答'
        }
      ],
      levelList: [
        {
          key: 0,
          value: '简单'
        },
        {
          key: 1,
          value: '正常'
        },
        {
          key: 2,
          value: '困难'
        }
      ],
      questionsList: [],
      selection: {},
      page: 1,
      pageSize: 10,
      course: '',
      totalPage: 0,
      dataListLoading: false,
      checkedAll: false,
      isAllCheck: false,
      disorder: null
    }
  },
  props: ['setExamData', 'examData', 'quesDisorder', 'setQuesDisorder'],
  components: { paperCate },
  methods: {
    changeQuesDisorder(e) {
      this.setQuesDisorder(e)
    },
    decode(val) {
      return decodeSrc(val)
    },
    setCurrent(data) {
      if (data.id) {
        this.current = data
        this.form.quesCateId = data.id
        this.$nextTick(_ => this.$refs['form'].validateField('quesCateId'))
      }
    },
    checkSort() {
      this.dialogFormVisible = true
      this.paperCate = true
      this.$nextTick(() => {
        this.$refs.paperCate.init(1)
      })
    },
    examDataAllList(val) {
      this.dataList.forEach(x => {
        x.status = val
        x.score = 1
      })
      if (this.selection[this.form.type]) {
        this.dataList.forEach(x => {
          this.selection[this.form.type].forEach((y, i) => {
            if (y.id === x.id) {
              this.selection[this.form.type].splice(i, 1)
              return false
            }
          })
        })
      }
      if (val) {
        this.selection[this.form.type] = this.selection[this.form.type]
          ? this.selection[this.form.type].concat(this.dataList)
          : this.dataList.map(x => x)
      }
      this.setExamData(this.selection)
    },
    examDataList(val, x) {
      x.status = val
      x.score = 1
      this.isAllCheck = !this.dataList.filter(x => x.status === false).length
      if (val) {
        if (this.selection[this.form.type]) {
          this.selection[this.form.type].push(x)
        } else {
          this.selection[this.form.type] = [x]
        }
      } else {
        this.selection[this.form.type] = this.selection[this.form.type].filter(
          i => i.id !== x.id
        )
      }
      this.setExamData(this.selection)
      this.$forceUpdate()
    },
    reset() {
      this.page = 1
      this.pageSize = 10
      this.totalPage = 0
      this.current = {}
      this.form = {
        keyword: '',
        quesCateId: '',
        type: '',
        quesLevel: ''
      }
      this.dataList = []
      this.isAllCheck = false
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.page = val
      this.getDataList()
    },
    // 查询获取数据
    getDataList() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.dataListLoading = true
          this.$http({
            url: this.$http.adornUrl('/exam-admin/ques/bank/list'),
            method: 'post',
            data: {
              page: this.page,
              limit: this.pageSize,
              quesType: this.form.type,
              quesLevel: this.form.quesLevel,
              keyword: this.form.keyword,
              quesCateId: this.form.quesCateId
            }
          })
            .then(res => {
              if (res.data) {
                this.dataList = res.data.list
                this.totalPage = res.data.totalCount
                this.page = res.data.currPage
                this.pageSize = res.data.pageSize
                try {
                  this.dataList.forEach(x => {
                    x.status = false
                    if (this.selection[this.form.type]) {
                      this.selection[this.form.type].forEach(y => {
                        if ((y.id || y.quesId) === x.id) {
                          x.status = true
                        }
                      })
                    }
                  })
                } catch (error) {
                  console.log(error.message)
                }
                console.log(
                  this.dataList.filter(x => x.status === false).length
                )
                this.isAllCheck = !this.dataList.filter(x => x.status === false)
                  .length
                this.dataListLoading = false
                this.$forceUpdate()
              } else {
                this.dataList = []
                this.totalPage = 0
                this.dataListLoading = false
              }
            })
            .catch(_ => {
              this.dataListLoading = false
            })
        }
      })
    },
    init(examData, course) {
      this.course = course
      this.reset()
      this.topicDialogVisible = true
      this.selection = examData
      this.$nextTick(_ => {
        this.disorder = this.quesDisorder
        this.addExamMain.height = `${this.$refs.addExamContent.$el
          .clientHeight - this.$refs.addExamHeader.$el.clientHeight}px`
        this.addExamMainList.height = `${this.$refs.addExamMain.$el
          .clientHeight -
          this.$refs.addExamMainH3.clientHeight -
          this.$refs.addExamMainFooter.clientHeight -
          this.$refs.addExamFooter.clientHeight}px`
      })
    },
    handleClose() {
      this.topicDialogVisible = false
    },
    onSubmit() {
      this.topicDialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.add-exam-list-select-h3 {
  margin: 0;
  padding: 10px 0;
  display: flex;
  align-items: center;
  font-size: 12px;
  font-weight: 400;
  color: #72767b;

  label {
    margin-right: 10px;
  }
}

.add-exam-list-select {
  height: 87%;
  list-style: none;
  font-weight: 300;
  color: #333;
  overflow: auto;

  &,
  ul,
  li,
  h3,
  h6,
  p {
    margin: 0;
    padding: 0;
  }

  & > li {
    padding: 10px 0;
    font-size: 13px;
    line-height: 30px;
    border-bottom: 1px solid #e9e9eb;

    &.noData {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 100%;
      font-size: 14px;
    }

    h3 {
      align-items: flex-start;
      color: black;
      font-size: 14px;

      label {
        margin-right: 30px;
      }
    }

    h6 {
      margin-left: 60px;
    }

    ul {
      padding-left: 60px;
      list-style: none;
      display: flex;
      flex-wrap: wrap;

      li {
        width: 50%;
      }
    }

    .add-exam-list-select-answer {
      margin-left: 60px;
    }

    .add-exam-list-select-analysis {
      margin-left: 60px;
      display: flex;
      padding: 10px 0;

      p {
        margin: 0;
      }

      p:last-of-type {
        flex: 1;
        height: 80px;
        line-height: 1;
        border: 1px solid #72767b;
        margin: 0 5px 0 30px;
        padding: 5px;
      }
    }
  }
}

.learn-drawer-range-box-buttons {
  &.add-exam-footer {
    border-top: 1px solid #333;
    padding: 10px;
  }
}
</style>
